#ifndef DATAVISUALIZATION_H
#define DATAVISUALIZATION_H

#include <QObject>
#include <QChart>
#include <QLineSeries>
#include <QBarSeries>
#include <QBarSet>
#include <QPieSeries>
#include <QValueAxis>
#include <QDateTimeAxis>
#include <QDateTime>
#include <QTimer>
#include "devicecontroller.h"
#include "samplingmanager.h"
#include "auditlogger.h"

QT_CHARTS_USE_NAMESPACE

// 图表类型枚举
typedef enum {
    CHART_FLOW_RATE = 0,    // 流量图表
    CHART_BATTERY_LEVEL,    // 电池电量图表
    CHART_SAMPLING_STATS,   // 采样统计图表
    CHART_DEVICE_STATUS,    // 设备状态图表
    CHART_TEMPERATURE,      // 温度图表
    CHART_HUMIDITY          // 湿度图表
} ChartType;

// 数据点结构体
typedef struct {
    QDateTime timestamp;    // 时间戳
    double value;          // 数值
    QString label;         // 标签
    int category;          // 分类
} DataPoint;

// 统计数据结构体
typedef struct {
    int total_samples;      // 总采样次数
    int successful_samples; // 成功采样次数
    int failed_samples;     // 失败采样次数
    double avg_flow_rate;   // 平均流量
    double total_volume;    // 总采样体积
    int total_time;         // 总采样时间
    QDateTime last_sample;  // 最后采样时间
} SamplingStatistics;

class DataVisualization : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QChart* flowRateChart READ getFlowRateChart NOTIFY flowRateChartChanged)
    Q_PROPERTY(QChart* batteryChart READ getBatteryChart NOTIFY batteryChartChanged)
    Q_PROPERTY(QChart* samplingStatsChart READ getSamplingStatsChart NOTIFY samplingStatsChartChanged)
    Q_PROPERTY(QVariant dashboardData READ getDashboardData NOTIFY dashboardDataChanged)

public:
    explicit DataVisualization(QObject *parent = nullptr);
    ~DataVisualization();

    // 初始化
    bool initialize(DeviceController* deviceController, 
                   SamplingManager* samplingManager, 
                   AuditLogger* auditLogger);

    // 图表获取方法
    Q_INVOKABLE QChart* getFlowRateChart();
    Q_INVOKABLE QChart* getBatteryChart();
    Q_INVOKABLE QChart* getSamplingStatsChart();
    Q_INVOKABLE QChart* getTemperatureChart();
    Q_INVOKABLE QChart* getHumidityChart();
    Q_INVOKABLE QChart* getDeviceStatusChart();
    
    // 数据更新方法
    Q_INVOKABLE void updateFlowRateData();
    Q_INVOKABLE void updateBatteryData();
    Q_INVOKABLE void updateSamplingStats();
    Q_INVOKABLE void updateAllCharts();
    
    // 历史数据查询
    Q_INVOKABLE QVariantList getFlowRateHistory(int hours) const;
    Q_INVOKABLE QVariantList getBatteryHistory(int hours) const;
    Q_INVOKABLE QVariantList getTemperatureHistory(int hours) const;
    Q_INVOKABLE QVariantList getHumidityHistory(int hours) const;
    
    // 统计数据获取
    Q_INVOKABLE QVariant getSamplingStatistics(int days) const;
    Q_INVOKABLE QVariant getDashboardData() const;
    Q_INVOKABLE QVariantList getDeviceStatusHistory(int hours) const;
    
    // 图表配置
    Q_INVOKABLE void setChartTimeRange(ChartType chartType, int hours);
    Q_INVOKABLE void setChartUpdateInterval(int seconds);
    Q_INVOKABLE void enableRealTimeUpdate(bool enabled);
    
    // 数据导出
    Q_INVOKABLE bool exportChartData(ChartType chartType, const QString& filePath) const;
    Q_INVOKABLE bool exportChartImage(ChartType chartType, const QString& filePath) const;
    
    // 图表样式设置
    Q_INVOKABLE void setChartTheme(int theme);
    Q_INVOKABLE void setChartColors(const QVariantList& colors);
    Q_INVOKABLE void setChartTitle(ChartType chartType, const QString& title);

signals:
    void flowRateChartChanged();
    void batteryChartChanged();
    void samplingStatsChartChanged();
    void dashboardDataChanged();
    void chartDataUpdated(ChartType chartType);
    void statisticsUpdated();

private slots:
    void onRealTimeUpdate();
    void onDeviceParametersChanged();
    void onSamplingCompleted();

private:
    // 私有成员变量
    DeviceController* m_deviceController;
    SamplingManager* m_samplingManager;
    AuditLogger* m_auditLogger;
    
    // 图表对象
    QChart* m_flowRateChart;
    QChart* m_batteryChart;
    QChart* m_samplingStatsChart;
    QChart* m_temperatureChart;
    QChart* m_humidityChart;
    QChart* m_deviceStatusChart;
    
    // 数据系列
    QLineSeries* m_flowRateSeries;
    QLineSeries* m_batterySeries;
    QLineSeries* m_temperatureSeries;
    QLineSeries* m_humiditySeries;
    QBarSeries* m_samplingStatsSeries;
    QPieSeries* m_deviceStatusSeries;
    
    // 坐标轴
    QDateTimeAxis* m_timeAxis;
    QValueAxis* m_valueAxis;
    
    // 定时器和配置
    QTimer* m_updateTimer;
    int m_updateInterval;
    int m_timeRangeHours;
    bool m_realTimeEnabled;
    
    // 数据存储
    QList<DataPoint> m_flowRateData;
    QList<DataPoint> m_batteryData;
    QList<DataPoint> m_temperatureData;
    QList<DataPoint> m_humidityData;
    QList<SamplingRecord> m_samplingHistory;
    
    // 私有方法 (使用C风格语法)
    void initializeCharts();
    void setupFlowRateChart();
    void setupBatteryChart();
    void setupSamplingStatsChart();
    void setupTemperatureChart();
    void setupHumidityChart();
    void setupDeviceStatusChart();
    
    void addDataPoint(ChartType chartType, double value, const QDateTime& timestamp);
    void removeOldDataPoints(ChartType chartType, int maxHours);
    void updateChartSeries(ChartType chartType);
    void updateChartAxes(QChart* chart, const QDateTime& minTime, const QDateTime& maxTime);
    
    // 数据处理方法
    SamplingStatistics calculateSamplingStatistics(int days) const;
    QVariantMap dataPointToVariant(const DataPoint& point) const;
    QVariantMap samplingStatisticsToVariant(const SamplingStatistics& stats) const;
    
    // 图表样式方法
    void applyChartTheme(QChart* chart, int theme);
    void setChartColors(QChart* chart, const QVariantList& colors);
    void configureChartAppearance(QChart* chart);
    
    // 数据持久化
    bool saveChartData(ChartType chartType) const;
    bool loadChartData(ChartType chartType);
    void createDataTables();
};

// C风格的辅助函数
extern "C" {
    const char* chartTypeToString(ChartType type);
    double calculateAverage(const DataPoint* points, int count);
    double calculateMaxValue(const DataPoint* points, int count);
    double calculateMinValue(const DataPoint* points, int count);
    int filterDataPointsByTime(const DataPoint* input, DataPoint* output, 
                              int inputCount, const QDateTime* startTime, const QDateTime* endTime);
}

#endif // DATAVISUALIZATION_H